package com.securities.stock.service.crawler;

import com.securities.stock.entity.dto.StockDto;
import com.securities.stock.entity.pojo.Concept;
import com.securities.stock.entity.pojo.Industry;
import com.securities.stock.entity.pojo.Stock;
import com.securities.stock.enums.ChannelEnum;
import com.securities.stock.utils.SSLHttpClientUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class CrawlerService {


    private static final Logger LOGGER = LoggerFactory.getLogger(CrawlerService.class);

    /****
     * 抓取流通股本和总股本
     * @param stock
     * @throws Exception
     */
    public Stock crawlerEquity(Stock stock) throws Exception{
        String url="http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_StockStructure/stockid/"+stock.getCode()+".phtml";
        String html = SSLHttpClientUtil.get(url);
        LOGGER.info("执行url={}, 返回结果={}",url,html.length());
        Document document = Jsoup.parse(html);// 解析列表页面
        Elements ltsz = document.select("#StockStructureNewTable0 tr");
        Element a = document.select("#toolbar h1 a").get(0);
        String name=a.text();
        Stock gbStock=new Stock();
        gbStock.setId(stock.getId());
        gbStock.setName(name);
        for(int i=0;i<ltsz.size();i++){
            Element tr = ltsz.get(i);
            if(i==5) {
                Elements tds = tr.children();
                if(tds.size()>1) {
                    String zgbName = tds.get(0).text();
                    //String zgbNameStr = new String(zgbName.getBytes("ISO8859-1"),"GBK");
                    String zgbNameStr = zgbName;
                    String zgbCount = tds.get(1).text();
                    //String zgbCountStr = new String(zgbCount.getBytes("ISO8859-1"),"GBK");
                    String zgbCountStr = zgbCount;
                    int indexOf = zgbCountStr.indexOf("万股");
                    if (indexOf > 0) {
                        String zgbNum = zgbCountStr.substring(0, indexOf);
                        BigDecimal zgbDecimal = new BigDecimal(zgbNum.trim()).multiply(new BigDecimal(10000));
                        LOGGER.info("{}:\t{}", zgbNameStr, zgbDecimal);
                        gbStock.setEquityTotal(zgbDecimal);
                    }
                }
            }
            if(i==7) {
                Elements tds = tr.children();
                if(tds.size()>1) {
                    String ltgName = tds.get(0).text();
                    //String ltgNameStr = new String(ltgName.getBytes("ISO8859-1"),"GBK");
                    String ltgNameStr = ltgName;
                    String ltgCount = tds.get(1).text();
                    //String ltgCountStr = new String(ltgCount.getBytes("ISO8859-1"),"GBK");
                    String ltgCountStr = ltgCount;
                    int indexOf = ltgCountStr.indexOf("万股");
                    if (indexOf > 0) {
                        String ltgNum = ltgCountStr.substring(0, indexOf);
                        BigDecimal ltgDecimal = new BigDecimal(ltgNum.trim()).multiply(new BigDecimal(10000));
                        LOGGER.info("{}:\t{}", ltgNameStr, ltgDecimal);
                        gbStock.setEquityCirculate(ltgDecimal);
                    }
                }
            }
        }
        return  gbStock;
    }

    public void crawlerBase() throws Exception{
        String url="http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_StockStructureHistory/stockid/600171/stocktype/LiuTongA.phtml";
        String html = SSLHttpClientUtil.get(url);
        LOGGER.info("执行url={}, 返回结果={}",url,html.length());
        Document document = Jsoup.parse(html);// 解析列表页面
        Elements ltsz = document.select("#toolbar div");
        for (Element tr : ltsz) {
            String s=tr.text();
            //String str = new String(s.getBytes("ISO8859-1"),"GBK");
            String str =s;
            LOGGER.info("ltsz：{}",str);
        }
    }
    //http://www.iwencai.com/stockpick/search?typed=1&preParams=&ts=1&f=1&qs=1&selfsectsn=&querytype=&searchfilter=&tid=stockpick&w=600119


    public static void crawlerConceptByTHS() throws Exception{
        String url="http://www.iwencai.com/stockpick/search?typed=1&preParams=&ts=1&f=1&qs=1&selfsectsn=&querytype=&searchfilter=&tid=stockpick&w=600119";
        String html = SSLHttpClientUtil.get(url);
        LOGGER.info("执行url={}, 返回结果={}",url,html);
        Document document = Jsoup.parse(html);// 解析列表页面
        Elements tds = document.select(".even_row click_tr td");
        for (Element tr : tds) {
            String s=tr.text();
            //String str = new String(s.getBytes("ISO8859-1"),"GBK");
            String str =s;
            LOGGER.info("td：{}",str);
        }
    }
    public StockDto crawlerConceptBySina(String code) throws Exception{
        StockDto stockDto=new StockDto();
        stockDto.setCode(code);
        String url="http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpOtherInfo/stockid/"+code+"/menu_num/5.phtml";
        String html = SSLHttpClientUtil.get(url);
        LOGGER.info("执行url={}, 返回结果={}",url,html.length());
        Document document = Jsoup.parse(html);// 解析列表页面
        Elements tables = document.select("#con02-0 table");
        if(tables.size()==2){
            //行业
            Element hyTable=tables.get(0);
            Elements hyTrs= hyTable.select("tr");
            if(hyTrs.size()>3){
                Element contentTr= hyTrs.get(2);
                Elements tds= contentTr.select("td");
                if(tds.size()>1) {
                    Element gnName = tds.get(0);
                    Element gnSameTd = tds.get(1);
                    if(gnSameTd!=null) {
                        Element gnSameA = gnSameTd.selectFirst("a");
                        LOGGER.info("所属行业={},同行业个股的url={}", gnName.text(), gnSameA.attr("href"));
                        Industry industry=new Industry();
                        industry.setIndustryName(gnName.text());
                        industry.setChannel(ChannelEnum.SINA.getChane());
                        industry.setChannelName(ChannelEnum.SINA.getChaneName());
                        industry.setSameUrl(ChannelEnum.SINA.getDomainUrl()+gnSameA.attr("href"));
                        if(!StringUtils.isEmpty(industry.getIndustryName())) {
                            stockDto.setStockIndustry(industry);
                        }
                    }
                }
            }
            //概念
            Element gnTable=tables.get(1);
            Elements gnTrs= gnTable.select("tr");
            if(!CollectionUtils.isEmpty(gnTrs)){
                List<Concept> concepts=new ArrayList<>();
                for(int i=0;i<gnTrs.size();i++){
                    //第一行是表头,第二行是说明
                    if(i>2){
                        Element contentTr= gnTrs.get(i);
                        Elements tds= contentTr.select("td");
                        Element gnName=tds.get(0);
                        Element gnSameTd=tds.get(1);
                        Element gnSameA= gnSameTd.selectFirst("a");
                        LOGGER.info("概念板块{}={},同概念个股的url={}",(i-2),gnName.text(),gnSameA.attr("href"));
                        Concept concept=new Concept();
                        concept.setConcepName(gnName.text());
                        concept.setChannel(ChannelEnum.SINA.getChane());
                        concept.setChannelName(ChannelEnum.SINA.getChaneName());
                        concept.setSameUrl(gnSameA.attr("href"));
                        if(!StringUtils.isEmpty(concept.getConcepName())) {
                            concepts.add(concept);
                        }
                    }
                }
                stockDto.setConcepts(concepts);
            }
        }
        return stockDto;
    }

    public static void main(String[] args) throws Exception {
        //crawlerConceptBySina();
    }

}
